<template>
  <div>
    <Top />
    <section class="bg-green-600 flex-col flex items-center justify-center" style="height: 10vh;text-align: center;">
      <div class="container mx-auto px-4">
        <div class="row">
          <div class="col-md-12 text-center">
            <h2 class="text-4xl font-bold text-white">Academic Achievements</h2>
          </div>
        </div>
      </div>
    </section>

    <div class="achievement-container">
      <!-- Tab导航 -->
      <div class="flex justify-center border-b border-gray-200 mb-8">
        <button
          @click="switchTab('business')"
          :class="[
            'flex items-center px-6 py-3 border-b-2 font-medium transition-colors cursor-pointer',
            activeTab === 'business'
              ? 'border-blue-500 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700'
          ]"
        >
          <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
          </svg>
          Publications
        </button>
        <button
          @click="switchTab('franchise')"
          :class="[
            'flex items-center px-6 py-3 border-b-2 font-medium transition-colors cursor-pointer',
            activeTab === 'franchise'
              ? 'border-blue-500 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700'
          ]"
        >
          <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h4a1 1 0 011 1v5m-6 0V9a1 1 0 011-1h4a1 1 0 011 1v11"></path>
          </svg>
          Academic communication
        </button>
        <button
          @click="switchTab('new')"
          :class="[
            'flex items-center px-6 py-3 border-b-2 font-medium transition-colors cursor-pointer',
            activeTab === 'new'
              ? 'border-blue-500 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700'
          ]"
        >
          <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4"></path>
          </svg>
          Press release
        </button>
      </div>

      <!-- 词云容器 -->
      <div class="wordcloud-container">
        <!-- 加载状态 -->
        <div v-if="isLoading" class="loading-container">
          <div class="loading-spinner"></div>
          <p>正在加载词云组件...</p>
        </div>

        <!-- 词云图表容器 -->
        <div v-show="!isLoading" class="charts-wrapper">
          <div
            key="business"
            v-show="activeTab === 'business'"
            :ref="el => { if (el) chartRefs.business = el }"
            class="chart-container"
            :style="{ minHeight: '600px', height: '600px' }"
          ></div>
          <div
            key="franchise"
            v-show="activeTab === 'franchise'"
            :ref="el => { if (el) chartRefs.franchise = el }"
            class="chart-container"
            :style="{ minHeight: '600px', height: '600px' }"
          ></div>
          <div
            key="new"
            v-show="activeTab === 'new'"
            :ref="el => { if (el) chartRefs.new = el }"
            class="chart-container"
            :style="{ minHeight: '600px', height: '600px' }"
          ></div>
        </div>
      </div>

      <!-- 详情模态框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="60%"
      >
        <div v-html="dialogContent"></div>
        <template #footer>
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button
            v-if="dialogUrl"
            type="primary"
            @click="openExternalLink"
          >
            查看原文
          </el-button>
        </template>
      </el-dialog>
    </div>
    <Bottom />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { articleApi } from '~/public/utils/api'

// 动态导入echarts和wordcloud插件，只在客户端执行
let echarts = null
let isClient = false

// 检查是否在客户端
if (typeof window !== 'undefined') {
  isClient = true
}
definePageMeta({
  layout: false
})

// 响应式数据
const activeTab = ref('business')
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogContent = ref('')
const dialogUrl = ref('')
const isLoading = ref(true)
const errorMessage = ref('')

// Tab配置已移至模板中

// 图表实例和数据
const charts = ref({})
const chartRefs = ref({})

// Tab到CategoryId的映射（参考原始配置）
const tabToCategoryId = {
  business: 4,
  franchise: 5,
  new: 6
}

// 颜色配置
const colorList = [
  '#3a96f5', '#5faaf7', '#78bafe', '#1563f2',
  '#add2f8', '#e24bf4', '#1acaff', '#ffde00',
  '#89fda5', '#FF0066', '#CC3399', '#66FFFF',
  '#FF00FF', '#66FF00'
]

// 蒙版图片配置
const maskImages = {
  business: '',
  franchise: '',
  new: ''
}

// 切换Tab
const switchTab = (tabKey) => {
  console.log('切换到tab:', tabKey)
  activeTab.value = tabKey
  // 清除错误信息
  errorMessage.value = ''
  if (isClient) {
    nextTick(() => {
      setTimeout(() => {
        console.log('开始渲染tab:', tabKey)
        renderChart(tabKey)
      }, 100) // 增加延迟时间，确保DOM完全切换
    })
  }
}

// 渲染图表
const renderChart = async (tabKey) => {
  // 只在客户端执行
  if (!isClient) return

  // 动态导入echarts和wordcloud
  if (!echarts) {
    try {
      const echartsModule = await import('echarts')
      echarts = echartsModule.default || echartsModule
      await import('echarts-wordcloud')
    } catch (error) {
      console.error('导入echarts失败:', error)
      return
    }
  }

  if (charts.value[tabKey]) {
    console.log(`销毁已存在的${tabKey}图表`)
    charts.value[tabKey].dispose()
    charts.value[tabKey] = null
  }

  const container = chartRefs.value[tabKey]
  if (!container) {
    console.error('容器未找到:', tabKey, 'chartRefs:', chartRefs.value)
    return
  }

  console.log('找到容器:', tabKey, container)

  // 确保容器有正确的尺寸
  container.style.width = '100%'
  container.style.height = '600px'
  container.style.minHeight = '600px'
  container.style.display = 'block'

  console.log('容器尺寸:', {
    width: container.offsetWidth,
    height: container.offsetHeight,
    clientWidth: container.clientWidth,
    clientHeight: container.clientHeight,
    display: getComputedStyle(container).display,
    visibility: getComputedStyle(container).visibility
  })

  // 如果容器尺寸为0，等待一下再试
  // if (container.offsetWidth === 0 || container.offsetHeight === 0) {
  //   console.log('容器尺寸为0，等待100ms后重试')
  //   setTimeout(() => renderChart(tabKey), 100)
  //   return
  // }

  const chart = echarts.init(container)
  charts.value[tabKey] = chart

  // 显示加载状态
  chart.showLoading({
    text: '正在加载数据',
    color: '#3d9c4d'
  })

  try {
    // 获取数据
    const data = await fetchChartData(tabKey)
    console.log(`${tabKey} 获取到的数据:`, data)

    // 创建蒙版图片
    const maskImage = new Image()
    maskImage.src = maskImages[tabKey]
    // 等待图片加载完成
    await new Promise((resolve) => {
      maskImage.onload = resolve
      maskImage.onerror = resolve
    })

    // 配置选项
    const option = createChartOption(data, maskImage, tabKey)

    chart.hideLoading()
    chart.setOption(option)

    // 确保图表正确调整大小
    setTimeout(() => {
      chart.resize()
    }, 100)

    // 添加点击事件
    chart.on('click', (params) => {
      handleChartClick(params, tabKey)
    })

  } catch (error) {
    chart.hideLoading()
    console.error('渲染图表失败:', error)
  }
}

// 获取图表数据
const fetchChartData = async (tabKey) => {
  const categoryId = tabToCategoryId[tabKey]

  try {
    // 调用真实API获取数据
    const result = await articleApi.getList({
      pageSize: 50, // 获取更多数据用于词云
      pageNum: 1,
      categoryId
    })

    // 检查返回状态码
    if (result?.code === 401) {
      navigateTo('/login')
      return []
    }

    // 检查其他错误状态码
    if (result?.code && result.code !== 200 && result.code !== 0) {
      const errorMsg = result?.msg || result?.message || `请求失败，错误码: ${result.code}`
      errorMessage.value = errorMsg
      console.error(`${tabKey} API错误:`, errorMsg)
      return []
    }

    const rows = result?.rows || result?.data?.rows || []

    console.log(`${tabKey} API返回的原始数据:`, result)
    console.log(`${tabKey} 提取的rows数据:`, rows)

    // 清除之前的错误信息
    errorMessage.value = ''

    // 转换真实数据为词云格式
    const convertedData = convertToWordCloudData(rows)
    console.log(`${tabKey} 转换后的数据:`, convertedData)
    return convertedData

  } catch (error) {
    console.error('获取数据失败:', error)
    // 检查错误响应中的状态码
    if (error?.response?.status === 401 || error?.code === 401) {
      navigateTo('/login')
      return []
    }

    // 设置错误信息
    const errorMsg = error?.response?.data?.msg || error?.message || '网络请求失败，请稍后重试'
    errorMessage.value = errorMsg
    return []
  }
}

// 转换API数据为词云数据格式
const convertToWordCloudData = (rows) => {
  // 直接返回原始数据，让getItemName函数处理字段提取
  return rows.map((row) => ({
    ...row, // 保留所有原始字段
    word_cloud_weight: row.word_cloud_weight || Math.random() * 50 + 10,
    originalData: row
  }))
}



// 创建图表配置
const createChartOption = (rawData, maskImage, tabKey) => {
  // 如果有错误信息，显示错误
  if (errorMessage.value) {
    return {
      title: {
        text: errorMessage.value,
        left: 'center',
        top: 'middle',
        textStyle: {
          fontSize: 16,
          color: '#f56c6c'
        }
      },
      grid: {
        left: 0, bottom: 0, top: 0, right: 0
      }
    }
  }

  // 如果没有数据，返回空配置
  if (!rawData || rawData.length === 0) {
    return {
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'middle',
        textStyle: {
          fontSize: 18,
          color: '#999'
        }
      },
      grid: {
        left: 0, bottom: 0, top: 0, right: 0
      }
    }
  }

  const data = rawData.map((item, index) => {
    // 先计算value值
    const value = item.word_cloud_weight || Math.random() * 50 + 10
    
    // 根据value值动态调整标题长度：value越大，字体越大，应该截取得更短
    const name = getItemName(item, tabKey, value)

    console.log(`${tabKey} 数据项 ${index}:`, {
      原始数据: item,
      提取的名称: name,
      权重值: value
    })

    return {
      name: name,
      value: value,
      uniscid: index,
      originalData: item
    }
  })

  // 根据不同tab设置不同的配置
  const configs = {
    business: {
      symbolSize: ['85.2%', '85.2%'],
      sizeRange: [15, 52],
      gridSize: 1,
      width: '85%',
      height: '85%'
    },
    franchise: {
      symbolSize: ['55.2%', '95.2%'],
      sizeRange: [10, 52],
      gridSize: 5,
      width: '55%',
      height: '95%'
    },
    new: {
      symbolSize: ['59.2%', '99.2%'],
      sizeRange: [10, 52],
      gridSize: 5,
      width: '59%',
      height: '99%'
    }
  }

  const config = configs[tabKey] || configs.business

  return {
    tooltip: {
      show: true,
      formatter: (params) => params.name
    },
    grid: {
      left: 0, bottom: 0, top: 0, right: 0
    },
    xAxis: { type: "category", show: false },
    yAxis: { max: 100, show: false },
    series: [
      {
        zlevel: -1,
        type: 'pictorialBar',
        name: 'pictorial',
        silent: true,
        symbol: 'image://' + maskImages[tabKey],
        symbolSize: config.symbolSize,
        symbolPosition: 'center',
        barWidth: '100%',
        barMaxWidth: '100%',
        itemStyle: {
          normal: { opacity: 0.1 }
        },
        data: [{ value: 100 }]
      },
      {
        type: 'wordCloud',
        sizeRange: config.sizeRange,
        rotationRange: [0, 0],
        maskImage: maskImage,
        textPadding: 0,
        gridSize: config.gridSize,
        width: config.width,
        height: config.height,
        left: 'center',
        top: 'center',
        drawOutOfBound: false,
        shrinkToFit: true,  // 如果字体太大放不下，自动缩小以适应空间
        textStyle: {
          fontFamily: "sans-serif",
          color: () => {
            const index = Math.floor(Math.random() * colorList.length)
            return colorList[index]
          }
        },
        data: data
      }
    ]
  }
}

// 获取项目名称
const getItemName = (item, tabKey, value) => {
  console.log('getItemName item:', item.title, 'value:', value)

  let title = item.title || 'Unknown'

  // 根据不同tab设置不同的基础文字长度限制
  const baseLengthConfig = {
    business: 45,
    franchise: 30,
    new: 25
  }
  
  let maxLength = baseLengthConfig[tabKey] || 25
  
  // 根据value值动态调整长度：value越大（字体越大），长度越短
  if (value > 40) {
    maxLength = Math.floor(maxLength * 0.7)  // 高权重：缩短到70%
  } else if (value > 30) {
    maxLength = Math.floor(maxLength * 0.85)  // 中高权重：缩短到85%
  }

  if (title.length > maxLength) {
    title = title.substring(0, maxLength) + '...'
  }

  console.log(`截取后的标题(${tabKey}, value=${value}, maxLength=${maxLength}):`, title)
  return title
}

// 处理图表点击
const handleChartClick = (params, tabKey) => {
  const item = params.data

  dialogTitle.value = getDialogTitle(item)
  dialogContent.value = getDialogContent(item)
  dialogUrl.value = getDialogUrl(item, tabKey)
  dialogVisible.value = true
}

// 获取对话框标题
const getDialogTitle = (item) => {
  // 获取原始数据，处理嵌套情况
  let originalData = item.originalData

  // 检查是否有嵌套的originalData
  if (originalData && originalData.originalData) {
    originalData = originalData.originalData
  }

  // 优先使用原始数据的title
  if (originalData?.title) {
    return originalData.title
  }

  // 如果没有原始数据，使用item的title
  return item.title || 'Details'
}

// 获取对话框内容
const getDialogContent = (item) => {
  // 如果有原始数据，优先使用原始数据
  let originalData = item.originalData

  // 检查是否有嵌套的originalData
  if (originalData && originalData.originalData) {
    originalData = originalData.originalData
  }

  if (originalData) {
    // 只使用detailed字段
    let detailed = originalData.detailed || '暂无详细内容'

    // 如果detailed是HTML，去除标签
    if (detailed && typeof detailed === 'string') {
      detailed = detailed.replace(/<[^>]+>/g, '')
    }

    console.log('原始数据:', originalData)
    console.log('提取的detailed:', detailed)

    return `
      <div>
        <div style="line-height: 1.6; color: #666;">${detailed}</div>
      </div>
    `
  }

  // 如果没有原始数据，使用默认格式
  return `
    <div>
      <div style="line-height: 1.6; color: #666;">暂无详细内容</div>
    </div>
  `
}

// 获取对话框URL
const getDialogUrl = (item, tabKey) => { // tabKey参数保留以保持函数签名一致性
  // 获取原始数据，处理嵌套情况
  let originalData = item.originalData

  // 检查是否有嵌套的originalData
  if (originalData && originalData.originalData) {
    originalData = originalData.originalData
  }

  // 获取文章ID，构建内部链接
  const articleId = originalData?.id || originalData?.articleId
  if (articleId) {
    return `/article/${articleId}`
  }

  return null
}

// 打开外部链接
const openExternalLink = () => {
  if (dialogUrl.value) {
    // 所有链接都在新窗口中打开
    window.open(dialogUrl.value, '_blank')
  }
}

// 组件挂载
onMounted(() => {
  // 确保在客户端执行
  if (isClient) {
    // 先设置加载状态为false，让DOM渲染
    isLoading.value = false

    // 等待DOM更新后再初始化图表
    nextTick(() => {
      setTimeout(async () => {
        try {
          console.log('开始初始化图表...')
          await renderChart(activeTab.value)
          console.log('图表初始化完成')
        } catch (error) {
          console.error('初始化失败:', error)
        }
      }, 100) // 给DOM一点时间完全渲染
    })
  } else {
    // 服务端渲染时也要设置为false，避免hydration不匹配
    isLoading.value = false
  }
})

// 组件卸载时清理
onUnmounted(() => {
  Object.values(charts.value).forEach(chart => {
    chart.dispose()
  })
})

// 设置页面标题
useHead({
  title: 'Achievements - Carbon Tariff Platform',
  meta: [
    { name: 'description', content: 'Explore our research achievements, business accomplishments, and academic contributions in carbon tariff and sustainability' },
    { name: 'keywords', content: 'carbon research achievements, business results, academic contributions, sustainability projects' }
  ]
})
</script>

<style scoped>
.achievement-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 80vh;
}

/* Tab样式已移至内联样式 */

.wordcloud-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin: 0 auto;
  max-width: 1200px;
  min-height: 600px;
}

.charts-wrapper {
  width: 100%;
  height: 600px;
  position: relative;
}

.chart-container {
  width: 100% !important;
  height: 600px !important;
  min-height: 600px !important;
  position: relative;
  display: block;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 600px;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3a96f5;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .achievement-container {
    padding: 10px;
  }

  .chart-container {
    height: 400px;
  }

  .tab-item {
    padding: 8px 16px;
    font-size: 14px;
    margin: 0 5px;
  }

  .wordcloud-container {
    margin: 0 10px;
  }
}

@media (max-width: 480px) {
  .tab-navigation {
    flex-direction: column;
    align-items: center;
  }

  .tab-item {
    margin: 5px 0;
    width: 200px;
    text-align: center;
  }

  .chart-container {
    height: 300px;
  }
}
</style>